<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="$route.meta.title" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <el-form class="ls-form" label-width="100px" ref="formRef" :model="formData" :rules="rules">
                <el-form-item label="客户姓名" prop="customer" label-width="120px">
                    <el-input
                        v-model="formData.customer"
                        placeholder="请输入"
                        class="config-key-input"
                    />
                </el-form-item>
                <el-form-item label="客户电话" prop="mobile" label-width="120px">
                    <el-input
                        v-model="formData.mobile"
                        placeholder="请输入"
                        class="config-key-input"
                    />
                </el-form-item>
                <el-form-item label="商品管理" v-perms="['order.orderGoods']">
                    <template #default="{ row }">
                        <div class="config-form">
                            <el-form v-for="(item, index) in formData.goods" :ref="(el) => setSkuFormRef(index, el)"
                                class="ls-form" :inline="true" :model="item" :rules="configItemRule"
                                style="display: flex;align-items: flex-start;flex-wrap: wrap;gap: 30px 0;">
                                <el-form-item label="选择商品规格" prop="goods_id" label-width="120px">
                                    <el-select v-model="item.goods_id" :data-index="index"
                                        @change="selectChange(item, index, $event)" placeholder="请选择" size="large"
                                        class="config-key-input" filterable>
                                        <el-option v-for="(item1, index1) in skusData" :label="item1.name"
                                            :value="item1.id" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="数量" prop="stock" label-width="120px">
                                    <el-input v-model="item.stock" placeholder="请输入" class="config-key-input" />
                                </el-form-item>
                                <el-form-item label="单位" prop="unit" label-width="120px">
                                    <span>{{ item.unit }}</span>
                                </el-form-item>
                                <el-form-item label="规格" prop="name" label-width="120px">
                                    <span>{{ item.name }}</span>
                                </el-form-item>

                                <el-form-item label="颜色" prop="color" label-width="120px">
                                    <span>{{ item.color }}</span>
                                </el-form-item>

                                <el-form-item label="型号" prop="type" label-width="120px">
                                    <span>{{ item.type }}</span>
                                </el-form-item>

                                <el-form-item label="盖帽颜色" prop="hat_color" label-width="120px">
                                    <span>{{ item.hat_color }}</span>
                                </el-form-item>

                                <el-form-item label="接口口径" prop="caliber" label-width="120px">
                                    <span>{{ item.caliber }}</span>
                                </el-form-item>

                                <el-form-item label="系列" prop="series" label-width="120px">
                                    <span>{{ item.series }}</span>
                                </el-form-item>

                                <el-form-item label="进水方式" prop="method" label-width="120px">
                                    <span>{{ item.method }}</span>
                                </el-form-item>

                                <el-form-item label="特殊型号" prop="special_type" label-width="120px">
                                    <span>{{ item.special_type }}</span>
                                </el-form-item>

                                <el-form-item label="高度" prop="height" label-width="120px">
                                    <span>{{ item.height }}</span>
                                </el-form-item>

                                <el-form-item label="片数" prop="number" label-width="120px">
                                    <span>{{ item.number == 0 ? '' : item.number }}</span>
                                </el-form-item>

                                <el-form-item label="组数" prop="group_number" label-width="120px">
                                    <span>{{ item.group_number == 0 ? '' : item.group_number }}</span>
                                </el-form-item>

                                <el-form-item label="销售单价" prop="sale_price" label-width="120px">
                                    <span>{{ item.sale_price == 0 ? '' : item.sale_price }}</span>
                                </el-form-item>

                                <el-form-item label="成本单价" prop="cost_price" label-width="120px">
                                    <span>{{ item.cost_price == 0 ? '' : item.cost_price }}</span>
                                </el-form-item>

                                <el-form-item label="备注" prop="remark" label-width="120px">
                                    <span>{{ item.remark }}</span>
                                </el-form-item>

                                <el-form-item prop="sale_number">
                                    <el-button type="danger" @click="formData.goods.splice(index, 1)">删除商品</el-button>
                                </el-form-item>
                            </el-form>

                            <el-button type="primary" @click="addConfigItem">添加商品项</el-button>
                        </div>
                    </template>
                </el-form-item>
                <el-form-item label="备注" prop="remark" label-width="120px">
                    <el-input
                        v-model="formData.remark"
                        type="textarea"
                        placeholder="请输入"
                        :rows="4"
                        class="config-key-textarea"
                    />
                </el-form-item>
                <div class="flex justify-center mt-4">
                    <el-button type="primary" @click="handleSubmit(formRef)">保存</el-button>
                    <el-button @click="$router.back()">取消</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import { goods_userAdd } from '@/api/repertory'
import { goodsLists } from '@/api/goods';
import feedback from '@/utils/feedback';
import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'
import config from '@/config'
const route = useRoute();
const router = useRouter();

const userStore = useUserStore()
const appStore = useAppStore()
const headers = computed(() => ({
    token: userStore.token,
    version: appStore.config.version
}))


const formData = reactive<{
    [key: string]: any
}>({
    goods: [],
    customer: '',
    mobile: '',
    type: 1,
    remark: '',
})

// 表单验证
const validateQuantityMustBeZero = (rule: any, value: any, callback: any) => {
  if (value == '' || value == null || Number(value) == 0) {
    callback(new Error('该值必须大于0'))
  } else {
    callback()
  }
}
const rules = reactive({
    customer: [
        {
            required: true,
            message: '请输入客户名称',
            trigger: 'blur'
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入客户联系方式',
            trigger: 'blur'
        },
        {
            pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
        }
    ]
})
const configItemRule = reactive({
    goods_id: [
        {
            required: true,
            message: '请选择商品',
            trigger: 'blur'
        }
    ],
    stock: [
        {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
        },
        { validator: validateQuantityMustBeZero, trigger: 'blur' }
    ]
    
})

const skusData = ref<any[]>([])
const getGoodsGet_skus = async () => {
    // const data  = await goodsGet_skus()
    const data = await goodsLists({ page_size: 9999 })
    skusData.value = data.lists
}



// 选中商品规格的处理

const selectChange = async (item: any, index: number, e: any) => {
    console.log(item, index, e)
    let data = skusData.value.find((item) => item.id == e)

    formData.goods[index].goods_id = data?.id
    for (const key in data) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData.goods[index][key] = data[key]
            if (key == 'sale_price' || key == 'cost_price') {
                formData.goods[index][key] = data && data[key] ? Number(data[key]) : 0
            }
            if (key == 'stock') {
                formData.goods[index][key] = 0
            }
        }
    }
}

// 声明表单 formRef
// 用来存储 SKU 表单 refs 的 Map
// Key 可以是 index 或 item.id (如果 item.id 唯一且稳定的话)
const skuFormRefs = ref(new Map());
// 设置 SKU 表单 ref 的函数
const setSkuFormRef = (index, el) => {
    if (el) {
        // 存储 el-form 组件实例
        skuFormRefs.value.set(index, el);
    } else {
        // 如果元素被移除，从 Map 中删除对应的 ref
        skuFormRefs.value.delete(index);
    }
};
// 可选：在更新前清空 refs，确保准确性（特别是当列表结构变化频繁时）
onBeforeUpdate(() => {
    skuFormRefs.value.clear();
});

// 表单提交
const formRef = ref<FormInstance>()
const formList = ref<any[]>([])
const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    if (formData.goods.length == 0) return feedback.msgError('请添加商品')
    let allValid = true;
    const formPromises = []; // 收集所有验证 Promise

    // 遍历 Map 中的所有表单实例
    for (const [index, formInstance] of skuFormRefs.value.entries()) {
        if (formInstance) {
            // 调用每个表单实例的 validate 方法
            // validate 方法返回一个 Promise
            formPromises.push(
                formInstance.validate().then((valid: boolean) => {
                    if (!valid) {
                        allValid = false;
                        console.log(`SKU表单 ${index} 验证失败.`);
                    } else {
                        console.log(`SKU表单 ${index} 验证通过.`);
                    }
                    return valid; // 返回验证结果
                }).catch((error: any) => {
                    allValid = false;
                    console.error(`验证 SKU表单 ${index} 时出错:`, error);
                    return false; // 发生错误也视为验证失败
                })
            );
        }
    }

    await Promise.all(formPromises);
    if (!allValid) {
        feedback.msgError('请填写必填项');
        return;
    }
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            formData.goods.forEach((item: any) => {
                formList.value.push({
                    goods_id: item.goods_id,
                    stock: item.stock
                })
            })
            let obj = {
                goods: formList.value,
                customer: formData.customer,
                mobile: formData.mobile,
                type: formData.type,
                remark: formData.remark,
            }
            await goods_userAdd(obj);
            feedback.msgSuccess('保存成功');
            router.back();
        } else {
            console.log('error submit!', fields);
        }
    });
};

// 添加配置项
const addConfigItem = () => {
    formData.goods.push({
        goods_id: '',
        stock: '',

        name: '',
        group_number: 0,
        number: 0,
        sale_price: 0,
        cost_price: 0,
        color: '',
        type: '',
        hat_color: '',
        caliber: '',
        series: '',
        height: '',
        method: '',
        special_type: '',
        remark: '',
        unit: ''
    })
}


onMounted(() => {
    getGoodsGet_skus()
});
</script>

<style scoped>
.config-key-input {
    width: 200px;
    height: 40px;
}
.config-key-textarea {
    width: 400px;
    height: 120px;
}
</style>